package com.lancoo.ccas52.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lancoo.ccas52.entity.*;
import com.lancoo.ccas52.mapper.RoomMapper;
import com.lancoo.ccas52.mapper.RoomTypeMapper;
import com.lancoo.ccas52.pojo.common.CollComparatorUtil;
import com.lancoo.ccas52.pojo.common.PageInfo;
import com.lancoo.ccas52.pojo.constant.GlobalConstant;
import com.lancoo.ccas52.pojo.dto.Building;
import com.lancoo.ccas52.pojo.response.basicPlatform.BaseCollege;
import com.lancoo.ccas52.pojo.response.digitization.BuildingInfo;
import com.lancoo.ccas52.pojo.vo.Campus;
import com.lancoo.ccas52.pojo.vo.RoomTypeDto;
import com.lancoo.ccas52.service.*;
import com.lancoo.ccas52.util.PagingUtil;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 教室 服务实现类
 * </p>
 *
 * @author quin.song
 * @since 2023-03-01
 */
@Service
public class RoomServiceImpl extends ServiceImpl<RoomMapper, Room> implements RoomService {

    @Resource
    private RoomMapper roomMapper;
    @Resource
    private TaskInfoService taskInfoService;

    @Resource
    private RuleRoomProhibitService ruleRoomProhibitService;
    @Resource
    private CollComparatorUtil<Room> collComparatorUtil;

    @Resource
    @Lazy
    private YunBasicService yunBasicService;
    @Resource
    private CollegeRoomService collegeRoomService;
    @Resource
    private RoomTypeMapper roomTypeMapper;
    @Resource
    private RoomService roomService;

    @Override
    public void syncRooms(Integer taskId, String schoolId, String term, List<BuildingInfo> buildingInfos) {
        List<Room> rooms = new ArrayList<>();
        if (CollUtil.isEmpty(buildingInfos)) {
            return;
        }
        //学院信息
        List<BaseCollege> baseCollege = yunBasicService.getCollege(taskId, schoolId);

        Map<String, String> college = baseCollege
                .stream().collect(Collectors.toMap(BaseCollege::getCollegeID, BaseCollege::getCollegeName));
        college.put(schoolId, "全部学院");
        for (BuildingInfo buildingInfo : buildingInfos) {
            for (BuildingInfo.BuildingFloorsDTO baseFloor : buildingInfo.getBuildingFloors()) {
                for (BuildingInfo.BuildingFloorsDTO.FloorRoomsDTO floorRoom : baseFloor.getFloorRooms()) {
                    BuildingInfo.BuildingFloorsDTO.FloorRoomsDTO.RoomInfoDTO baseRoom = floorRoom.getRoomInfo();
                    //只同步可以排课的教室类型
                    if (GlobalConstant.roomTypeMap.containsKey(baseRoom.getFunctionType())) {
//                        if(schoolId.equals(baseRoom.getCollegeId())){
//                            baseRoom.setCollegeId(null);
//                        }
                        rooms.add(new Room()
                                .setTaskId(taskId)
                                .setBaseRoomId(baseRoom.getRoomId())
                                .setRoomName(baseRoom.getRoomName())
                                .setCollegeId(baseRoom.getCollegeId())
                                .setCollegeName(college.get(baseRoom.getCollegeId()))
                                .setBuildingFloor(baseFloor.getBuildFloor())
                                .setBuildingId(buildingInfo.getBuildingInfo().getBuildingId())
                                .setBuildingName(buildingInfo.getBuildingInfo().getBuildingName())
                                .setBaseRoomType(baseRoom.getFunctionType())
                                .setRoomNum(baseRoom.getSeatCount().equals(0)?Integer.MAX_VALUE:baseRoom.getSeatCount())
                                .setCampusId(schoolId + baseRoom.getCampus())
                                .setCampusName(baseRoom.getCampus())
                                .setSchoolId(schoolId)
                                .setTerm(term)
                                .setIsEnable(1)
                        );

                    }

                }
            }
        }

        List<Room> oldRoomList = this.lambdaQuery().eq(Room::getSchoolId, schoolId).eq(Room::getTerm, term).list();
        List<Room> addRoom = collComparatorUtil.getAdded(oldRoomList, rooms);

        if (CollUtil.isNotEmpty(addRoom)) {
            roomMapper.addBatch(addRoom);
        }
    }

    @Override
    public List<RoomTypeDto> getRoomType(String schoolId, String term, Integer type) {
//        List<RoomTypeDto> roomTypeList = roomMapper.getRoomType(schoolId, term);
//        //默认AI智慧教室 放在列表第一位
//        List<RoomTypeDto> first = roomTypeList.stream()
//                .filter(dto -> dto.getRoomType() == 21)
//                .collect(Collectors.toList());
//        roomTypeList.removeAll(first);
//        roomTypeList.addAll(0, first);
//
//        roomTypeList.forEach(roomTypeDto -> roomTypeDto.setRoomTypeName(GlobalConstant.roomTypeMap.get(roomTypeDto.getRoomType())));

        if (type != null && type == 1){
            return roomTypeMapper.getRoomType(schoolId,term,null);
        }
        if (type == null){
            List<Integer> types = roomService.getRoomTypeUsed(schoolId,term);
            return roomTypeMapper.getRoomType(schoolId,term,types);
        }
        return new ArrayList<>();
    }

    @Override
    public List<Building> getBuilding(String schoolId, String term) {
        return roomMapper.getBuilding(schoolId, term);
    }

    @Override
    public List<Integer> getFloor(String schoolId, String term, Integer buildingId) {
        return roomMapper.getFloor(schoolId, term, buildingId);
    }

    @Override
    public List<Campus> getCampusList(Integer taskId) {
        //todo 直接修改传参
        TaskInfo taskInfo = taskInfoService.getById(taskId);
        return roomMapper.getCampusList(taskInfo.getSchoolId(), taskInfo.getTerm());
    }

    @Override
    public PageInfo<Room> getRoomList(IPage<Room> page, String schoolId, String term,String collegeId, String campusId, Integer buildingId, Integer buildingFloor, Integer roomType, String keyword, Integer state,Integer isEnable) {
        IPage<Room> roomPage = roomMapper.getRuleRoom(page, schoolId, term, campusId, buildingId, buildingFloor, roomType, keyword, state,isEnable);

        List<Long> roomIds = roomPage.getRecords().stream().map(Room::getRoomId).collect(Collectors.toList());
        //禁排时间
        if (roomIds.size() > 0) {
            Map<Long, List<RuleRoomProhibit>> ruleMap = ruleRoomProhibitService.lambdaQuery().eq(RuleRoomProhibit::getSchoolId, schoolId).eq(RuleRoomProhibit::getTerm, term)
                    .in(RuleRoomProhibit::getRoomId, roomIds).eq(RuleRoomProhibit::getCollegeId,collegeId).list()
                    .stream().collect(Collectors.groupingBy(RuleRoomProhibit::getRoomId));
            roomPage.getRecords().forEach(room -> {
                room.setRuleRoomProhibitList(ruleMap.get(room.getRoomId()));
            });
        }
        return PagingUtil.formatPageResult(roomPage);
    }

    @Override
    public List<Room> getRoomSimpleList(String schoolId, String term, Integer buildingId, Integer buildingFloor, String keyword, String campusId,Integer roomType,Integer taskId,Integer isEnable,String collegeId) {
        List<Room> list = this.lambdaQuery().eq(Room::getSchoolId, schoolId)
                .eq(Room::getTerm, term)
                .eq(ObjUtil.isNotNull(buildingId), Room::getBuildingId, buildingId)
                .eq(ObjUtil.isNotNull(buildingFloor), Room::getBuildingFloor, buildingFloor)
                .eq(StrUtil.isNotBlank(campusId), Room::getCampusId, campusId)
                .eq(ObjUtil.isNotNull(roomType), Room::getRoomType, roomType)
                .eq(ObjUtil.isNotNull(isEnable), Room::getIsEnable, isEnable)
                .like(StrUtil.isNotBlank(keyword), Room::getRoomName, keyword)
                .list();
        //获取指定院系设置的场地范围.未获取到数据默认全部教室
        if (StrUtil.isNotBlank(collegeId)) {
            List<CollegeRoom> collegeRoomList = collegeRoomService.lambdaQuery().eq(CollegeRoom::getTaskId, taskId)
                    .eq(CollegeRoom::getCollegeId, collegeId).list();
            if (CollUtil.isNotEmpty(collegeRoomList)) {
                List<Long> roomIds = collegeRoomList.stream().map(CollegeRoom::getRoomId).collect(Collectors.toList());
                list = list.stream().filter(room -> roomIds.contains(room.getRoomId())).collect(Collectors.toList());
            }
        }
        return list;
    }

    @Override
    public List<Integer> getRoomTypeUsed(String schoolId, String term) {
        return baseMapper.getRoomTypeUsed(schoolId,term);
    }
}
